package io.gbznt.modules.buss.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import io.gbznt.common.utils.*;
import io.gbznt.modules.sys.service.SysDeptService;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import io.gbznt.common.constant.Variable;
import io.gbznt.common.validator.ValidatorUtils;
import io.gbznt.common.validator.group.AddGroup;
import io.gbznt.common.validator.group.UpdateGroup;
import io.gbznt.modules.buss.entity.BussKnowledgeBaseEntity;
import io.gbznt.modules.buss.service.BussKnowledgeBaseService;
import io.gbznt.modules.sys.entity.SysDeptEntity;

/**
 * 知识库
 *
 * @author gbznt
 * @email http://www.gbznt.com/
 * @date 2019-04-20 15:48:33
 */
@RestController
@RequestMapping("buss/bussknowledgebase")
public class BussKnowledgeBaseController {
	@Autowired
	private BussKnowledgeBaseService bussKnowledgeBaseService;
	@Autowired
	private SysDeptService sysDeptService;

	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("buss:bussknowledgebase:list")
	public R list(@RequestParam Map<String, Object> params) {
		PageUtils page = bussKnowledgeBaseService.queryPage(params);
		return R.ok().put("page", page);
	}

	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("buss:bussknowledgebase:info")
	public R info(@PathVariable("id") String id) {
		BussKnowledgeBaseEntity bussKnowledgeBase = bussKnowledgeBaseService.getById(id);

		return R.ok().put("bussKnowledgeBase", bussKnowledgeBase);
	}

	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("buss:bussknowledgebase:save")
	public R save(@RequestBody BussKnowledgeBaseEntity bussKnowledgeBase) {
		ValidatorUtils.validateEntity(bussKnowledgeBase, AddGroup.class);

		bussKnowledgeBase.setCreateId(ShiroUtils.getUserId() + "");
		bussKnowledgeBase.setCreateTime(new Date());
		bussKnowledgeBase.setCreateName(ShiroUtils.getUserName());
		bussKnowledgeBaseService.save(bussKnowledgeBase);

		return R.ok();
	}

	/**
	 * 保存
	 */
	@RequestMapping("/saveFileAndData")
	@RequiresPermissions("buss:bussknowledgebase:save")
	public R saveFileAndData(BussKnowledgeBaseEntity bussKnowledgeBase, HttpServletRequest request) {

		MultipartFile multipartFile = null;
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request,
					MultipartHttpServletRequest.class);
			multipartFile = multipartRequest.getFile("file");

			if (null == multipartFile) {// 有更改文件
				return R.error("未上传文件");
			}
		}

		String rootPath = FileConfigReader.getUploadFilePath();
		R createDirRes = DocUtil.createDir(multipartFile, rootPath);
		if ((Integer) createDirRes.get("code") != 0) {
			return createDirRes;
		}

		File insertFile = (File) createDirRes.get("insertFile");
		try {
			multipartFile.transferTo(insertFile);
		} catch (IllegalStateException e) {
			e.printStackTrace();
			return R.error("上传文件出错!!!");
		} catch (IOException e) {
			e.printStackTrace();
			return R.error("上传文件出错");
		}

		SysDeptEntity dept = (SysDeptEntity) ShiroUtils.getSessionAttribute(Variable.LOGIN_USER_DEPART.getValue());
		bussKnowledgeBase.setDeptId(dept.getId());
		bussKnowledgeBase.setCreateId(ShiroUtils.getUserId());
		bussKnowledgeBase.setCreateTime(new Date());
		bussKnowledgeBase.setFileName(multipartFile.getOriginalFilename());
		bussKnowledgeBase.setFilePath(insertFile.getPath());
		bussKnowledgeBase.setCreateName(ShiroUtils.getUserName());

		ValidatorUtils.validateEntity(bussKnowledgeBase, AddGroup.class);
		Boolean re = bussKnowledgeBaseService.save(bussKnowledgeBase);

		return re ? R.ok() : R.oldVersion();
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("buss:bussknowledgebase:update")
	public R update(@RequestBody BussKnowledgeBaseEntity bussKnowledgeBase) {
		ValidatorUtils.validateEntity(bussKnowledgeBase, AddGroup.class);

		bussKnowledgeBase.setUpdateId(ShiroUtils.getUserId() + "");
		bussKnowledgeBase.setUpdateTime(new Date());
		bussKnowledgeBase.setUpdateName(ShiroUtils.getUserName());
		Boolean re = bussKnowledgeBaseService.updateById(bussKnowledgeBase);// 全部更新

		return re ? R.ok() : R.oldVersion();
	}

	/**
	 * 修改
	 */
	@RequestMapping("/updateFileAndData")
	@RequiresPermissions("buss:bussknowledgebase:update")
	public R updateFileAndData(BussKnowledgeBaseEntity bussKnowledgeBase, HttpServletRequest request) {
		MultipartFile multipartFile = null;
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request,
					MultipartHttpServletRequest.class);
			multipartFile = multipartRequest.getFile("file");

			if (null != multipartFile) {// 有更改文件
				String rootPath = FileConfigReader.getUploadFilePath();
				R createDirRes = DocUtil.createDir(multipartFile, rootPath);
				if ((Integer) createDirRes.get("code") != 0) {
					return createDirRes;
				}

				File insertFile = (File) createDirRes.get("insertFile");
				try {
					multipartFile.transferTo(insertFile);
				} catch (IllegalStateException e) {
					e.printStackTrace();
					return R.error("上传文件出错!!!");
				} catch (IOException e) {
					e.printStackTrace();
					return R.error("上传文件出错");
				}
				bussKnowledgeBase.setFilePath(insertFile.getPath());
				bussKnowledgeBase.setFileName(multipartFile.getOriginalFilename());
			}
		}

		ValidatorUtils.validateEntity(bussKnowledgeBase, UpdateGroup.class);

		bussKnowledgeBase.setUpdateId(ShiroUtils.getUserId());
		bussKnowledgeBase.setUpdateTime(new Date());
		bussKnowledgeBase.setUpdateName(ShiroUtils.getUserName());
		Boolean re = bussKnowledgeBaseService.updateById(bussKnowledgeBase);// 全部更新
		return re ? R.ok() : R.oldVersion();
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("buss:bussknowledgebase:delete")
	public R delete(@RequestBody String[] ids) {
		// 只会删除没有子集的
		List<String> str = new ArrayList<>();
		for (String id : ids) {
			QueryWrapper<BussKnowledgeBaseEntity> qw = new QueryWrapper<BussKnowledgeBaseEntity>();
			qw.eq("menu_id", id);
			List<BussKnowledgeBaseEntity> list = bussKnowledgeBaseService.list(qw);
			if (list.size() < 1) {// 有子集size就会>0
				str.add(id);
			}
		}
		if (str.size() > 0 && !str.get(0).equals("1")) {
			bussKnowledgeBaseService.removeByIds(str);
		}

		return R.ok();
	}

	/**
	 * 获取知识库所有的目录菜单
	 */
	@RequestMapping("/getAll")
	public List<BussKnowledgeBaseEntity> getAll() {
		QueryWrapper<BussKnowledgeBaseEntity> ew = new QueryWrapper<BussKnowledgeBaseEntity>();
		ew.eq("type", 0);
		// 个人数据权限控制
		ew.in(!Constant.SUPER_ADMIN.equals(ShiroUtils.getUserId()),
				"dept_id", sysDeptService.getPermissionDeptIdsArr(true,true));
		ew.or(!Constant.SUPER_ADMIN.equals(ShiroUtils.getUserId()));
		ew.eq(!Constant.SUPER_ADMIN.equals(ShiroUtils.getUserId()),"id","1");

		ew.orderByDesc("create_time");
		List<BussKnowledgeBaseEntity> list = bussKnowledgeBaseService.list(ew);

		return list;
	}

}
